<!DOCTYPE html>
<html lang="en">

<head>
  <title>Web OTP API Simplest</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <script src="https://cdn.bootcss.com/vConsole/3.3.4/vconsole.min.js"></script>
  <script>
    // 初始化
    var vConsole = new VConsole();
  </script>
</head>

<body>
  <input type="text" autocomplete="one-time-code" inputmode="numeric" />
  <script>
    if ("OTPCredential" in window) {
      console.log(111, window.OTPCredential);
      window.addEventListener("DOMContentLoaded", (e) => {
        const input = document.querySelector('input[autocomplete="one-time-code"]');
        if (!input) return;
        const ac = new AbortController();
        const form = input.closest("form");
        if (form) {
          form.addEventListener("submit", (e) => {
            ac.abort();
          });
        }
        console.log(222, { ac });
        console.log(222, { form });
        console.log(222, navigator.credentials);
        navigator.credentials
          .get({
            otp: { transport: ["sms"] },
            signal: ac.signal,
          })
          .then((otp) => {
            console.log(333, otp);
            input.value = otp.code;
            if (form) form.submit();
          })
          .catch((err) => {
            console.error(err);
          });
      });
    }
  </script>
</body>

</html>